%%%-------------------------------------------------------------------
%%% @author Administrator
%%% @copyright (C) 2019, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 31. 12月 2019 14:15
%%%-------------------------------------------------------------------
-module(msg_tbniuniu).
-author("Administrator").
-include("../include/protocol.hrl").
-include("../include/logger.hrl").
-include("../include/game.hrl").
-include("../include/myshare.hrl").
-include("../include/player.hrl").

%% API
-export([message_response/3]).

message_response(FormId, _Msg, #room_status{ws_conn_pid = Ws_Pid})
  when FormId /= Ws_Pid ->
  ok;

message_response(FormId, Msg, RoomState = #room_status{player_id = PlayerId, ws_conn_pid = Ws_Pid})
  when FormId =:= Ws_Pid ->
  try
    Map = jsx:decode(Msg, [return_maps, {labels, atom}]),
    Code = maps:get(code, Map),
    ?DEBUG("MSG info code:~p,Data:~p", [Code, Map]),
    CodeList = [?NIUNIU_BOTTOM, ?NIUNIU_JOIN_TABLE, ?NIUNIU_CHECKOUT, ?WEINIU_BET, ?WEINIU_SPEAK],
    Data =
      case maps:is_key(data, Map) of
        true -> maps:get(data, Map);
        _ -> #{}
      end,
    UserId =
      case is_map(Data) of
        true -> maps:get(userId, Data, 0);
        _ -> 0
      end,
    case lists:member(Code, CodeList) of
      true ->
        msg_hand(Code, Data, RoomState);
      _ ->
        case UserId =:= list_to_binary(PlayerId) orelse UserId =:= 0 of
          true ->
            ?DEBUG("FormId:~p;msg:~ts~n", [FormId, Msg]),
            msg_hand(Code, Data, RoomState);
          _ -> ok
        end
    end
  catch
    Class:Error:Stacktrace ->
      ?ERROR("game msg_tbniuniu error class:~p;error:~p;stacktrace:~p", [Class, Error, Stacktrace])
  end.

msg_hand(Code, Data, RoomState = #room_status{player_id = PlayerId, room_id = RoomId2, account = Account,
  player_state = PlayerRoomState}) ->
  PlayerPid = list_to_atom("pid_" ++ Account),
  case Code of
    ?NIUNIU_INDEX ->
      ?DEBUG("room index info account:~p", [Account]),
      Players = [Player || Player <- Data, is_map(Player)],
      ?DEBUG("niuniu index players:~p", [Players]),
      %获取座位号
      Index =
        case RoomState#room_status.is_look_bet of
          true -> undefined;
          _ ->
            game_assist:get_room_index(Players, list_to_binary(PlayerId), RoomState#room_status.game_id)
        end,
      Index2 =
        case Index of
          undefined -> 0;
          _ -> Index
        end,
      NewState2 = RoomState#room_status{index = Index2},
      self() ! {update_state, NewState2},

      case RoomState#room_status.is_integral of
        true ->
          case RoomState#room_status.is_look_bet of
            true -> self() ! {look_bet};
            _ -> self() ! {join_table}
          end;
        _ ->
          if
            RoomState#room_status.is_look_bet =:= true -> Queue = false;
            Index =:= undefined ->
              Queue = true;
            true -> Queue = false
          end,
          integral_join_table(NewState2, Queue)
      end;
    ?NIUNIU_NOT_ROOM ->
      ?ERROR("not this room ");
    %进入房间
    ?NIUNIU_INTO_ROOM ->
      database:update_player_state([RoomState#room_status.game_id, RoomId2, Account]),
      scheduling:player_into_room(RoomId2),
      case RoomState#room_status.game_id of
        ?WEI_NIU ->
          WeiNiuPlayers = maps:get(players, Data),
          case game_assist:get_weiniu_zj(WeiNiuPlayers) of
            {0, 0} ->
              ok;
            {Zj_Id, Zj_index} ->
              ?DEBUG("in room put zhuangjia user id:~p;index:~p", [Zj_Id, Zj_index]),
              erlang:put(?ZJ_USER, #{user_id => Zj_Id, index => Zj_index})
          end,
          erlang:put(?ZJ_TASK_COMPLETE, false),
          UpZhuangScoreType = maps:get(upZhuangScoreType, Data),
          Zz_Money =
            case UpZhuangScoreType of
              0 -> 50;
              _ -> UpZhuangScoreType * 100
            end,
          erlang:put(?ZJ_SCORE_POOL, Zz_Money),
          erlang:put(?ZZ_MONEY, Zz_Money);
        _ -> ok
      end,
      gen_server:call(PlayerPid, {update_state, {into_room}}),
      case RoomState#room_status.is_look_bet of
        true ->
          ?INFO("player look bet account:~p", [RoomState#room_status.account]),
          integral_join_table(Data, RoomState, false);
        _ ->
          %房间玩家信息
          RoomId = binary_to_integer(maps:get(id, Data)),
          Players = maps:get(players, Data),
          %获取座位号
          Index = gen_server:call(mainPID, {index_number, [Players, list_to_binary(PlayerId), RoomState#room_status.game_id]}),
          case Index of
            error -> ?ERROR("get index error");
            _ ->
              ?INFO("join room success account:~p;index:~p,roomID:~p", [Account, Index, RoomId2]),
              game_assist:insert_player_into_room(Account, RoomId),
              case Index of
                %%旁观排队
                undefined ->
                  ?INFO("robot be queuing: ~p;~p", [Account, Index]),
                  case gen_server:call(PlayerPid, {queue}) of
                    {ok, Index2} ->
                      ?INFO("robot be queuing integral_join_table : ~p;~p", [Account, Index2]),
                      NewState2 = RoomState#room_status{player_state = ?QUEUE, index = Index2},
                      self() ! {update_state, NewState2},
                      integral_join_table(Data, NewState2, true);
                    _ ->
                      ?INFO("queue Line error playerId:~p", [PlayerId])
                  end;
                _ ->
                  NewState2 = RoomState#room_status{player_state = ?LOOK, index = Index},
                  self() ! {update_state, NewState2},
                  integral_join_table(Data, NewState2, false)
              end

          end
      end;
    ?NIUNIU_QUEUE_INFO ->
      ?DEBUG("NIUNIU_QUEUE_INFO account:~p;data:~p", [Account, Data]);

%退出房间
    ?NIUNIU_OUT_ROOM ->
      case list_to_binary(PlayerId) of
        Data ->
          ?INFO("out room success ~p", [PlayerId]),
          player_assist:delete_queue(RoomId2, PlayerId),
          self() ! {update_state, RoomState#room_status{player_state = ?LOBBY}},
          gen_server:call(PlayerPid, {update_state, {out_room}}),
          scheduling:player_out_room(RoomId2),
          database:update_player_state(["0", "0", Account]);
        _ -> ok
      end;

    ?NIUNIU_QUEUE ->
      ?DEBUG("NIUNIU_QUEUE msg :~p,account:~p", [Data, Account]),
      QueuePlayerId = maps:get(id, Data, 0),
      %通比和三公加入旁观下注
      case list_to_binary(PlayerId) of
        QueuePlayerId ->
          GameId2 = RoomState#room_status.game_id,
          case lists:member(GameId2, [?NIU_NIU, ?SAN_GONG, ?WEI_NIU]) of
            true ->
              ?DEBUG("Add Bet on the sidelines account:~p", [Account]),
              self() ! {look_bet};
            _ -> ok
          end;
        _ -> ok
      end;

%进入桌子押注
    ?NIUNIU_JOIN_TABLE ->
      ?DEBUG("NIUNIU_JOIN_TABLE account:~p,data:~p", [Account, Data]),
      NewIndex = maps:get(index, Data),
      UserId = maps:get(userId, Data),
      case list_to_binary(PlayerId) of
        UserId ->%删除排队
          ?INFO("join table success playerid:~p;index11:~p", [Account, NewIndex]),
          player_assist:delete_queue(RoomId2, PlayerId),
          %修改状态
          self() ! {update_state, RoomState#room_status{is_queue = false, index = NewIndex, player_state = ?SEAT}};
        _ ->
          %%其他玩家进入桌子
          ok
      end;

%站起旁观
    ?NIUNIU_STAND_LOOK ->
      case list_to_binary(PlayerId) of
        Data ->
          ?DEBUG("NIUNIU_STAND_LOOK account:~p", [Account]),
          self() ! {update_state, RoomState#room_status{player_state = ?LOOK}},
          case erlang:get(?IS_ZJ) of
            true ->
              erlang:put(?IS_ZJ, false),
              self() ! {checkout};
            _ -> ok
          end;
        _ ->
          %%更新座位信息
          ok
      end;
    ?NIUNIU_LOOK_BET ->
      case list_to_binary(PlayerId) of
        Data ->
          ?DEBUG("NIUNIU_LOOK_BET account:~p", [Account]),
          self() ! {update_state, RoomState#room_status{player_state = ?LOOK_BET}};
        _ -> ok
      end;
    ?NIUNIU_PLAYER_BET ->
      ?INFO("NIUNIU_PLAYER_BET success");

    ?NIUNIU_DAILY_MSG ->
      ?INFO("NIUNIU_DAILY_MSG success");

    ?NIUNIU_EMOJI ->
      ?INFO("NIUNIU_EMOJI success");

%带入积分
    ?NIUNIU_INTO_INTEGRAL ->
      ?INFO("NIUNIU_INTO_INTEGRAL success account:~p,player_state:~p;is_look_bet:~p",
        [Account, RoomState#room_status.player_state, RoomState#room_status.is_look_bet]),
      case RoomState#room_status.is_integral of
        false ->
          if
            RoomState#room_status.is_look_bet =:= true ->
              self() ! {look_bet};
            RoomState#room_status.player_state =:= ?SEAT -> ok;
            true ->
              ?DEBUG("player join_table account:~p", [Account]),
              self() ! {join_table}
          end;
        _ -> ok
      end,
      Take_number = erlang:get(?TAKE_NUMBER),

      erlang:put(?TAKE_NUMBER, Take_number + 1),
      Score = maps:get(score, Data),
      %记录首次带入
      case Take_number of
        0 ->
          erlang:put(?FIRST_INTO, Score);
        _ -> ok
      end,
      Integral = RoomState#room_status.into_integral + Score,
      Room_score = RoomState#room_status.room_score + Score,
      Left_score = RoomState#room_status.left_score - Score,
      self() ! {update_state, RoomState#room_status{is_integral = true, into_integral = Integral,
        room_score = Room_score, left_score = Left_score}};

%押注准备 20s
    ?NIUNIU_SET_BET ->
      ?DEBUG("NIUNIU_SET_BET player room state:~p,account:~p", [PlayerRoomState, Account]),
      case PlayerRoomState of
        ?SEAT ->
          ?INFO("set bet 20s"),
          player_bet(RoomState);
        ?LOOK_BET ->
          N = random_number:generate_random(14),
          Plate = abs(RoomState#room_status.plate),
          Room_Score = RoomState#room_status.room_score,
          Money = game_assist:bet_type_money(?OTHER_MONEY, Plate, Room_Score),
          ?DEBUG("NIUNIU_SET_BET send_after set bet,account:~p;time:~p;money:~p;plate:~p;Into_Score:~p",
            [Account, N, Money, Plate, Room_Score]),
          Index3 = random_number:generate_random(10),
          ?DEBUG("Look bet account:~p;index:~p", [Account, Index3]),
          erlang:send_after((N + 1) * 1000, self(), {look_player_bet, Index3 - 1, ?BEY_NORMAL, Money});
        _ -> ok
      end;
    ?NIUNIU_START_GAME ->
      ?INFO("start game set bet 20s"),
      player_bet(RoomState);
    ?NIUNIU_BOOKING ->
      ok;

    %%通比准备亮牌4-7秒
    ?NIUNIU_CHIP ->
      ?DEBUG("NIUNIU_CHIP:~p", [Data]),
      case RoomState#room_status.game_id of
        ?NIU_NIU_MING_PAI ->
          Puke = maps:get(puke, Data),
          ?DEBUG("mingpai card puke:~p", [Puke]),
          scheduling:licensing(#ming_pai_player{account = Account, room_id = RoomId2, match = Puke});
        _ -> ok
      end,

      case PlayerRoomState =:= ?SEAT andalso lists:member(RoomState#room_status.game_id, [?NIU_NIU, ?SAN_GONG]) =:= true of
        true ->
          N = random_number:generate_random(4),
          ?INFO("TONBI NIUNIU_LP success,account:~p;num:~p", [Account, N]),
          erlang:send_after((5 + N) * 1000, self(), {booking});
        _ -> ok
      end;
    %牌局结果
    ?NIUNIU_RESULT ->
      ?DEBUG("NIUNIU_RESULT,account:~p;data:~p", [Account, Data]),
      {LeftScore, Score} = game_assist:profit_calculation(PlayerId, Data),%房间余额，输赢结果
      case game_assist:profit_calculation(PlayerId, Data) of
        {0, 0} ->
          ?DEBUG("other player NIUNIU_RESULT"),
          ok;
        {LeftScore, Score} ->
          ?DEBUG("niuniu ret left_score:~p; score:~p; account:~p", [LeftScore, Score, Account]),
          TotalPlate = RoomState#room_status.total_plate + Score,
          ?DEBUG("playerid: ~p;LeftScore:~p", [PlayerId, LeftScore]),
          self() ! {update_state, RoomState#room_status{plate = abs(Score),
            room_score = LeftScore, total_plate = TotalPlate}},
          %%激情围牛赔付池
          case RoomState#room_status.game_id of
            ?WEI_NIU ->
              ZjScorePool = maps:get(zjScorePool, Data),
              erlang:put(?ZJ_SCORE_POOL, ZjScorePool);
            ?NIU_NIU_MING_PAI ->
              erlang:erase(RoomId2),
              scheduling:results(Account);
            _ -> ok
          end,
          Min_integral = game_assist:take_min_integral(Account, RoomId2),%最低带入积分
          Take_number = erlang:get(?TAKE_NUMBER),
          Task_take_number = game_assist:get_take_integral_num(RoomState#room_status.task_id),
          Condition = game_assist:get_task_condition(RoomState#room_status.task_id),
          ?DEBUG("Take_number ~p; account :~p", [Take_number, Account]),
          case game_assist:threshold(Condition, TotalPlate) of
            true ->
              %%完成任务
              PlayerPid ! {task_complete};
            _ ->
              %查看余额补入积分
              First_into = erlang:get(?FIRST_INTO),

              ?DEBUG("paiju ret add integral score:~p;min_integral:~p;task_number:~p;take_number:~p,First_into:~p",
                [LeftScore, Min_integral, Task_take_number, Take_number, First_into]),
              Min_num =
                case is_number(First_into) of
                  true -> First_into * 0.2;
                  _ -> Min_integral
                end,
              if
                LeftScore < Min_num andalso Task_take_number > Take_number ->
                  ?INFO("Add integral; Account:~p ,number:~p", [Account, Take_number]),
                  self() ! {into_integral};
                LeftScore < Min_integral * 0.3 andalso Task_take_number =< Take_number ->
                  %%补入积分次数用完退出游戏
                  ?INFO("Fill in the points used up, exit the game; Account:~p ", [Account]),
                  PlayerPid ! {task_complete};
                true ->
                  ok
              end
          end
      end;

    ?RES_CODE_SYSTEM_MSG_PULL -> ok;%%系统消息
    %结算离开房间
    ?NIUNIU_CHECKOUT ->
      ?INFO("NIUNIU_CHECKOUT success ~p ;; ~p", [PlayerId, Data]),
      UserId = maps:get(userId, Data),
      case list_to_binary(PlayerId) of
        UserId ->
          New_left_score = RoomState#room_status.left_score + RoomState#room_status.room_score,
          self() ! {update_state, RoomState#room_status{is_integral = false, player_state = ?LOBBY,
            left_score = New_left_score, wn_select = false}},
          gen_server:call(PlayerPid, {update_state, {out_room}}),
          database:update_player_state(["0", "0", Account]),
          {Login_sate, Killing} = gen_server:call(PlayerPid, {get_login_state}),
          ?DEBUG("player checkout: ~p", [Login_sate]),
          %%如果是踢下线的就不空出座位，不补人
          case Killing of
            true -> ok;
            _ -> scheduling:player_out_room(RoomId2)
          end,
          case Login_sate of
            true ->
              ?INFO("Enter the integral complete, exit the game"),
              gen_server:cast(PlayerPid, {stop});
            _ -> ok
          end;
        _ -> ok
      end;

%网络错误
    ?NIUNIU_NET_ERROR ->
      ?ERROR("TONGBI_NIUNIU net error account:~p;msg:~ts~n", [Account, Data]),
      Tc_msg = unicode:characters_to_binary("请退出房间,重新加入"),
      Money_msg = unicode:characters_to_binary("下注金币不足"),
      Place_some = unicode:characters_to_binary("当前位置已有人"),
      _Money_msg2 = unicode:characters_to_binary("积分不足无法入座"),

      case Data of
        Tc_msg -> ?ERROR("error msg Re-enter the room"),
          self() ! {out_room};
        Money_msg -> ?ERROR("Short of betting gold");
        Place_some ->
          Time = random_number:generate_random_time(6),
          erlang:send_after(Time, self(), {room_index_info});
        _ ->
          ?ERROR("other error")
      end;

    ?NIUNIU_POUNDAGE ->
      ?ERROR("Lack of club leverage account :~p,data:~p", [Account, Data]);
    ?NIUNIU_CUTTING ->
      ?DEBUG("NIUNIU_CUTTING");
    ?NIUNIU_PLAYER_INFO ->
      ?DEBUG("NIUNIU_PLAYER_INFO~p", [Data]);

    %%明牌发牌
    ?NIUNIU_DEAL ->
      ?DEBUG("NIUNIU_DEAL: ~p", [Data]);

    %%抢庄阶段 牛牛，牛九，特殊牌型必抢4
    ?NIUNIU_ROB_ZHUANG ->
      ?INFO("NIUNIU_ROB_ZHUANG:~p", [Data]),
      %%根据所有玩家牌型计算该玩家抢庄倍数
      timer:sleep(2000),
      Is_BiQiang =
        case game_util:get_puke(Account) of
          [] -> false;
          #ming_pai_player{match = Match} ->
            N3 = game_util:get_bet_num(Match),
            case N3 >= 3 of
              true -> true;
              _ -> false
            end
        end,
      N =
        case Is_BiQiang of %是否必抢
          true ->
            erlang:put(RoomId2, true),
            4;
          _ -> game_util:ming_pai_zhuang_number(RoomId2, Account)
        end,
      After_Time = sys_util:random(4),
      erlang:send_after((After_Time + 1) * 1000, self(), {rob_zhuang, N});

    %%明牌闲家下注
    ?NIUNIU_BOTTOM ->
      UserId = maps:get(userId, Data),
      ?DEBUG("NIUNIU_ROB_ZHUANG SUCCESS ,~p", [Data]),
      PlayerId2 = list_to_binary(PlayerId),
      if
        UserId /= PlayerId2 ->
          Push = maps:get(push, Data),
          PidAtom = list_to_atom(PlayerId),
          IsPush = maps:fold(
            fun(K, _V, AccIn) ->
              if
                AccIn =:= true -> AccIn;
                K =:= PidAtom -> true;
                true -> AccIn
              end
            end,
            false, Push),
          %%获取当前玩家牌型
          N =
            case game_util:get_puke(Account) of
              [] -> 1;
              Ming_pai ->
                %%下注倍数计算
                N2 = game_util:get_bet_num(Ming_pai#ming_pai_player.match),
                case N2 of
                  1 -> 1;
                  99 ->
                    if
                      IsPush =:= false -> 3;
                      true ->
                        99
                    end;
                  N_1 -> N_1
                end
            end,
          After_Time = random_number:generate_random(4),
          case N of
            1 ->
              case random_number:generate_random(3) of
                3 -> ok;
                _ ->
                  erlang:send_after(After_Time * 1000, self(), {rob_bottom, N})
              end;
            _ ->
              erlang:send_after(After_Time * 1000, self(), {rob_bottom, N})
          end;

        true ->
          ?INFO("You are the banker."),
          ok
      end;
%%%明牌准备亮牌
    ?NIUNIU_LP ->
      ?DEBUG("MINGPAI booking ret account:~p;state:~p,data:~p", [Account, PlayerRoomState, Data]),
      case PlayerRoomState of
        ?SEAT ->
          S =
            case RoomState#room_status.game_id of
              ?NIU_NIU_MING_PAI -> 10;
              ?WEI_NIU -> 6;
              _ -> 9
            end,
          N = sys_util:random(S),
          Num = N * 1000,
          ?INFO("minpai NIUNIU_LP success,account:~p,num:~p", [Account, Num]),
          erlang:send_after(Num, self(), {booking});
        _ -> ok
      end;

%%围牛下注
    ?WEINIU_BET ->
      ?DEBUG("WEINIU_BET account:~p;PlayerRoomState:~p,Data:~p", [Account, PlayerRoomState, Data]),
      case RoomState#room_status.wn_select of
        false ->
          ZJ_SCORE_POOL = erlang:get(?ZJ_SCORE_POOL),
          ZZ_money = erlang:get(?ZZ_MONEY),
          ?DEBUG("WEINIU_BET ZJ_SCORE_POOL :~p", [ZJ_SCORE_POOL]),
          {Type, Money} = game_assist:weiniu_bet_money(ZZ_money, ZJ_SCORE_POOL),
          N = random_number:generate_random(7),
          GameMoney = game_assist:integral(Money),
          ?DEBUG("weiniu bet money:~p,account:~p", [GameMoney, Account]),
          case PlayerRoomState of
            ?SEAT ->
              case is_shoot() of
                true ->
                  ?DEBUG("WEINIU_BET shoot account:~p", [Account]),
                  ShootMoney = erlang:round(ZJ_SCORE_POOL) div 3,
                  erlang:send_after((N + 1) * 1000, self(), {weiniu_bottom, ShootMoney, 22, true});
                _ ->
                  erlang:send_after((N + 1) * 1000, self(), {weiniu_bottom, GameMoney, Type, false})
              end;
            ?LOOK_BET ->
              IndexZj = maps:get(index, Data),
              erlang:send_after((N + 1) * 1000, self(), {weiniu_look_bottom, GameMoney, Type, IndexZj});
            _ -> ok
          end;
        _ -> ok
      end;

%获取发言者
    ?WEINIU_GET_SPEAK ->
      case list_to_binary(PlayerId) of
        Data ->
          ?DEBUG("WEINIU_GET_SPEAK account:~p;data:~p", [Account, Data]),
          speak();
        _ -> ok
      end;
%%四把后重新发言
    ?WEINIU_RE_SPEAK ->
      erlang:put(?RE_FY_TYPE, 2),
      PlayerId2 = list_to_binary(PlayerId),
      case maps:get(faYanUser, Data) of
        PlayerId2 -> repeat_speak();
        _ -> ok
      end;

%%爆庄重新发言
    ?WEINIU_BAOZHUANG ->
      erlang:put(?RE_FY_TYPE, 1),
      PlayerId2 = list_to_binary(PlayerId),
      case maps:get(faYanUser, Data) of
        PlayerId2 -> repeat_speak();
        _ -> ok
      end;

%%围牛发言结果
    ?WEINIU_SPEAK ->
      ?DEBUG("WEINIU_SPEAK account:~p; data:~p", [Account, Data]),
      case Data =:= #{} of
        true ->
          ok;
        _ ->
          UserId = maps:get(userId, Data),
          Select = maps:get(select, Data),
          IsLz = maps:get(isLianZhuang, Data),
          case IsLz of
            true ->
              case
                erlang:get(?RE_FY_TYPE) of
                1 ->
                  NewMoney = (erlang:get(?ZZ_MONEY) * 2) + erlang:get(?ZJ_SCORE_POOL),
                  erlang:put(?ZJ_SCORE_POOL, NewMoney);
                _ -> ok
              end;
            _ ->
              ?DEBUG("WEINIU_BET ZJ_SCORE_POOL 33333 ~p", [erlang:get(?ZZ_MONEY)]),
              erlang:put(?ZJ_SCORE_POOL, erlang:get(?ZZ_MONEY)),
              Zj_Index = game_assist:get_player_index(RoomId2, UserId),
              erlang:put(?ZJ_USER, #{user_id => UserId, index => Zj_Index})
          end,

          case list_to_binary(PlayerId) =:= UserId andalso Select =:= true of
            true ->
              ?DEBUG("WEINIU_SPEAK shangzhuang account:~p", [Account]),
              erlang:put(?IS_ZJ, true),
              self() ! {update_state, RoomState#room_status{wn_select = true}};
            _ ->
              ?DEBUG("WEINIU_SPEAK guozhuang account:~p", [Account]),
              self() ! {update_state, RoomState#room_status{wn_select = false}}
          end
      end;
    ?NIUNIU_CHIP_DIS ->
      ?INFO("NIUNIU_CHIP_DIS");

%心跳包
    ?NIUNIU_HEART_BEAT ->
      ?INFO("NIUNIU_HEART_BEAT");
    _ ->
%%      ?DEBUG("Other Protocol"),
      ok
  end.

%%是否射门
is_shoot() ->
  Money = erlang:get(?ZJ_SCORE_POOL),
  if
    Money > 500 andalso Money < 1000 ->
      N = sys_util:random(2);
    Money < 100 ->
      N = 0;
    true ->
      N = sys_util:random(10)
  end,
  case N of
    1 -> true;
    _ -> false
  end.


%%重复发言
repeat_speak() ->
  SCORE_POOL = erlang:get(?ZJ_SCORE_POOL),
  if
    SCORE_POOL > 3000 ->
      erlang:send_after(2000, self(), {weiniu_guozhuang});
    SCORE_POOL < 1000 ->
      erlang:send_after(2000, self(), {weiniu_speak});
    true -> speak()
  end.

%%发言
speak() ->
  N = sys_util:random(10),
  ?DEBUG("speak number:~p", [N]),
  Zj_task_complete = erlang:get(?ZJ_TASK_COMPLETE),
  case lists:member(N, [1]) =:= true orelse Zj_task_complete =:= true of
    true ->
      ?DEBUG("weiniu_guozhuang======"),
      erlang:send_after(2000, self(), {weiniu_guozhuang});
    _ ->
      ?DEBUG("weiniu_speak======"),
      erlang:send_after(2000, self(), {weiniu_speak})
  end.


%%押注
player_bet(RoomState) ->
  case RoomState#room_status.is_queue of
    true ->
      ?INFO("player_bet player is queue"),
      ok;
    _ ->
      N = random_number:generate_random(14),
      BetList = game_assist:bet_algorithm(N, RoomState#room_status.plate),
      %百分之一概率切牌
      case sys_util:random(100) of
        50 -> self() ! {cutting};
        _ -> ok
      end,

      Min_money = game_assist:take_min_integral(RoomState#room_status.account, RoomState#room_status.room_id),

      lists:foreach(
        fun(Acc2) ->
          {Time, Type} = Acc2,
          Time_s = Time * 1000,
          if
            Type =:= ?SAIL ->
              ?DEBUG("kaichuang,account:~p", [RoomState#room_status.account]),
              erlang:send_after(Time_s, self(), {player_bet, ?BEY_SAIL, 0});
            true ->
              Plate = abs(RoomState#room_status.plate),
              Room_Score = RoomState#room_status.room_score,%余额
              Money = game_assist:bet_type_money(Type, Plate, Room_Score),
              if
                Min_money =:= 0 -> Money2 = 100;
                Money < Min_money -> Money2 = Min_money;
                true -> Money2 = Money
              end,
              ?DEBUG("send_after set bet,account:~p;time:~p;type:~p;money:~p;plate:~p;Into_Score:~p",
                [RoomState#room_status.account, Time_s, Type, Money2, Plate, Room_Score]),
              erlang:send_after(Time_s, self(), {player_bet, ?BEY_NORMAL, Money2})
          end
        end, BetList)
  end.


%%带入积分入桌
integral_join_table(Data, NewSate, Is_Queue) ->
  RoomState = NewSate#room_status{
    game_count = maps:get(gameCount, Data),
    status = binary_to_list(maps:get(status, Data)),
    left_room_time = maps:get(leftRoomTime, Data),
    current_time = maps:get(currentTime, Data),
    room_max_time = maps:get(roomMaxTime, Data),
    is_queue = Is_Queue
  },
  ?DEBUG("integral_join_table IN sate:~p", [RoomState]),
  self() ! {update_state, RoomState},
  case RoomState#room_status.is_integral of
    false ->
      ?INFO("intgeral join table"),
      self() ! {into_integral};%带入积分并入座
    _ ->
      ?INFO("not intgeral join table"),
      self() ! {join_table}%已经带入积分，直接入座
  end.


integral_join_table(NewSate, Is_Queue) ->
  RoomState = NewSate#room_status{
    is_queue = Is_Queue
  },
  ?DEBUG("integral_join_table IN sate:~p", [RoomState]),
  self() ! {update_state, RoomState},
  case RoomState#room_status.is_integral of
    false ->
      ?INFO("intgeral join table"),
      self() ! {into_integral};%带入积分并入座
    _ ->
      ?INFO("not intgeral join table"),
      self() ! {join_table}%已经带入积分，直接入座
  end.












